package com.goods.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.HealthMapper;
import com.goods.business.service.HealthService;
import com.goods.common.model.business.Health;
import com.goods.common.model.system.User;
import com.goods.common.vo.system.PageVO;
import com.goods.system.mapper.UserMapper;
import com.wuwenze.poi.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @author XiaoHong
 * @description
 * @date 2022/2/18
 */
@Service
public class HealthServiceImpl implements HealthService {
    @Autowired
    private HealthMapper healthMapper;

    @Autowired
    private UserMapper userMapper;
    //是否已经报备过了
    @Override
    public Health isReport(String username) {
        User user = getUser(username);
        Example exampleHealth = new Example(Health.class);
        Example.Criteria criteriaHeath = exampleHealth.createCriteria();
        String dateNow = DateUtil.format("yyyy-MM-dd", new Date());

        //创建当前时间
        Date date = new Date();
        criteriaHeath.andEqualTo("userId",user.getId());
        List<Health> healthList = healthMapper.selectByExample(exampleHealth);
        for (Health health : healthList) {
            if (dateNow.equals(DateUtil.format("yyyy-MM-dd", health.getCreateTime()))){
                //如果存在
                return health;
            }
        }
        return null;
    }

    //立即打卡
    @Override
    public void report(Health health, String username) {
        User user = getUser(username);
        health.setCreateTime(new Date());
        health.setUserId(user.getId());
        healthMapper.insert(health);
    }

    //获取当前用户
    private User getUser(String username) {
        //查询userId
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        return userMapper.selectOneByExample(example);
    }

    //签到记录
    @Override
    public PageVO<Health> history(String username, Integer pageSize, Integer pageNum) {
        User user = getUser(username);
        Long id = user.getId();
        PageHelper.startPage(pageNum,pageSize);
        //根据usrId 获取记录
        Example exampleHealth = new Example(Health.class);
        Example.Criteria criteriaHeath = exampleHealth.createCriteria();
        criteriaHeath.andEqualTo("userId",user.getId());
        List<Health> healthList = healthMapper.selectByExample(exampleHealth);
        PageInfo<Health> healthPageInfo = new PageInfo<Health>(healthList);

        return new PageVO<>(healthPageInfo.getTotal(),healthList);
    }
}
